<?php

namespace Install\Controller;

use Think\Storage;

/**
 * 部署安装
 * @author ZXZ <zxz054321@163.com>
 */
class IndexController extends InstallController {

    private $lockFile = './install.lock';

    public function _initialize() {
        parent::_initialize();

        /* 安装锁 */
        if (!APP_DEBUG) {//部署模式下禁止重复安装
            if (Storage::has($this->lockFile)) {
                $this->error('不可重复安装！');
            }
        }
    }

    public function index() {
        $this->moduleList = C('MODULE_LIST');
        $this->addonList = C('ADDON_LIST');
        $this->display();
    }

    public function install() {
        $buffer = ini_get('output_buffering');
        echo str_repeat(' ', $buffer + 1); //防止浏览器缓存
        ob_end_flush();     //关闭缓存
        echo $this->fetch();
        flush(); //刷新缓存（直接发送到浏览器）

        $this->_installModules();
        $this->_installAddons();

        // 写入安装锁定文件
        Storage::put($this->lockFile, 'lock');

        $this->redirect('success');
    }

    private function _installModules() {
        $class = get_module_class('Install');
        $module = new $class;
        $module->install();

        $db = M('Modules');
        foreach (C('MODULE_LIST') as $module) {
            $class = get_module_class($module);
            $module = new $class;

            $module->install();

            if ($module->checkInfo()) {
                $db->create($module->info);
                $db->add();
            }
        }
    }

    private function _installAddons() {
        $db = M('Addons');
        foreach (C('ADDON_LIST') as $addon) {
            $class = get_addon_class($addon);
            $addon = new $class;

            $addon->install();

            if ($addon->checkInfo()) {
                $db->create($addon->info);
                if ($db->add()) {
                    D('Hooks')->updateHooks($addon->info['name']);
                }
            }
        }
    }

}
